 //
//  SISSFindPassengerCooperationViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/4/18.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSFindPassengerCooperationViewController.h"
#import "SISSComboBoxView.h"
#import "SISSFindPassengerCooperationCell.h"
#import "SISSRequestCooperationView.h"
#import "SISSPassengerCooperationDetailViewController.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSChatViewController.h"
#import "SISSPassengerCooperationModel.h"

static NSString *findPassengerCooperationCellReuseID = @"findPassengerCooperationCellReuseID";
@interface SISSFindPassengerCooperationViewController ()<SISSComboBoxViewDelegate,UITableViewDelegate,UITableViewDataSource,SISSFindPassengerCooperationCellDelegate,SISSRequestCooperationViewDelegate>

/** tableView */
@property (weak, nonatomic) SISSBaseTableView *tableView;
/* hintLabel */
@property (weak, nonatomic) UILabel *hintLabel;
/** 房源合作数组 */
@property (strong, nonatomic) NSMutableArray<SISSPassengerCooperationModel *> *passengerCooperationArr;


/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** 合作范围 */
@property (copy, nonatomic) NSArray *cooperationRange;


/** 点击cell的indexPath */
@property (copy, nonatomic) NSIndexPath *indexPath;

@end

@implementation SISSFindPassengerCooperationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNo = 1;
//    [self requestPassengerResourceCooperationData];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
    
    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
        [weakSelf reloadMoreData];
    }];
    self.tableView.mj_footer.hidden = YES;
}

- (void)setKeyword:(NSString *)keyword {
    _keyword = keyword;
    self.pageNo = 1;
    [self requestPassengerResourceCooperationData];
}



#pragma mark - 代理
#pragma mark -- SISSComboBoxViewDelegate 筛选
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestPassengerResourceCooperationData];
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestPassengerResourceCooperationData];
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"合作范围"]) {
        self.cooperationRange = @[];
        self.cooperationRange = subtitles;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = @[];
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = @[];
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = @[];
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    self.pageNo = 1;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    [self requestPassengerResourceCooperationData];
    
    self.cooperationRange = @[];
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWithMessage:@"没有找到相关合作..." ifNecessaryForRowCount:self.passengerCooperationArr.count];
    return self.passengerCooperationArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SISSFindPassengerCooperationCell *cell = [tableView dequeueReusableCellWithIdentifier:findPassengerCooperationCellReuseID forIndexPath:indexPath];
    
    cell.delegate = self;
    cell.passengerCooperationModel = self.passengerCooperationArr[indexPath.row];
    
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    return 153;
//}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    SISSPassengerCooperationDetailViewController *vc = [[SISSPassengerCooperationDetailViewController alloc] init];
//    vc.isFindCooperation = YES;
//    vc.title = @"客源合作详情";
//    [self.navigationController pushViewController:vc animated:YES];

    NSDictionary *parameters = @{
                                 @"adcrId":self.passengerCooperationArr[indexPath.row].acrId
                                 };
    [kNetworkManager requestPassengerCooperationDetailWithparameters:parameters success:^(SISSPassengerCooperationDetailModel *passengerCooperationModel) {
        
        SISSPassengerCooperationDetailViewController *vc = [[SISSPassengerCooperationDetailViewController alloc] init];
        vc.isFindCooperation = YES;
        vc.title = @"客源合作详情";
        vc.passengerCooperationModel = passengerCooperationModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];

}

#pragma mark -- SISSFindHouseCooperationCellDelegate 联系人、请求合作按钮
// 点击联系人按钮
- (void)findPassengerCooperationCell:(SISSFindPassengerCooperationCell *)cell clickContactButton:(UIButton *)button {
    
    NSLog(@"客源=点击联系人按钮");
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    SISSChatViewController *chatVC = [[SISSChatViewController alloc] initWithConversationChatter:self.passengerCooperationArr[indexPath.row].imAccount conversationType:EMConversationTypeChat];
    SISSContactModel *model = [[SISSContactModel alloc] init];
    model.name = self.passengerCooperationArr[indexPath.row].name;
    model.portrait = self.passengerCooperationArr[indexPath.row].portrait;
    model.spId = self.passengerCooperationArr[indexPath.row].spId;
    model.accountType = 1;
    chatVC.contactModel = model;
    chatVC.title = self.passengerCooperationArr[indexPath.row].name;
    [self.navigationController pushViewController:chatVC animated:YES];
}

// 点击请求合作按钮
- (void)findPassengerCooperationCell:(SISSFindPassengerCooperationCell *)cell clickRequestCooperationButton:(UIButton *)button {
    
    NSLog(@"客源=点击请求合作按钮");
    
    self.indexPath = [self.tableView indexPathForCell:cell];
    
    SISSRequestCooperationView *requestView = [[SISSRequestCooperationView alloc] init];
    requestView.delegate = self;
    requestView.cooperationTextStr = @"我对您发布的客源合作很感兴趣想和您进一步沟通，请求同意合作。";
}

#pragma mark -- SISSRequestCooperationViewDelegate 点击请求合作
- (void)requestCooperationViewClickConfirmButtonWithCooperationReason:(NSString *)cooperationReason {
    NSLog(@"cooperationReason: %@",cooperationReason);
    
//    NSString *cooperationReasonStr = [NSString unicodeToISO88591:cooperationReason];
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"adcrId":self.passengerCooperationArr[self.indexPath.row].acrId,
                                 @"cooperation_desc":cooperationReason
                                 };
    [kNetworkManager requestPassengerCooperationRequestWithparameters:parameters success:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) { // 请求合作成功
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVSuccessTitle:@"请求合作成功" andTime:2 andColor:YES];
//                EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.passengerCooperationArr[self.indexPath.row].id_no type:EMConversationTypeChat createIfNotExist:YES];
                EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:cooperationReason];
                
                EMMessage *message = [[EMMessage alloc] initWithConversationID:self.passengerCooperationArr[self.indexPath.row].imAccount from:[SISSUserAccount shared].imAccount to:self.passengerCooperationArr[self.indexPath.row].imAccount body:body ext:nil];
                [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *error) {
                    
                    
                }];

                [self requestPassengerResourceCooperationData];
            }];
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

#pragma mark - 点击事件
#pragma mark -- 点击排序按钮
- (void)sortedButtonDidClick:(UIButton *)button {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    [alertController addTapDisMissAction];
    
    NSArray *sortArr = @[@"默认排序", @"人员星级从高到低", @"服务评价从高到低", @"预算从低到高", @"预算从高到低"];
    
    for (int i = 0; i < sortArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:sortArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.orderAttrs = i;
            kSISSRefresh.refreshType = SISSRefressTypeUpDown;
            [self requestPassengerResourceCooperationData];
        }];
        
        [alertController addAction:action];
    }
    
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    self.pageNo = 1;
    [self requestPassengerResourceCooperationData];
}

- (void)reloadMoreData {
    
    self.pageNo += 1;
    [self requestPassengerResourceCooperationData];
}

#pragma mark - 加载数据
- (void)requestPassengerResourceCooperationData {
    
    // 非空处理
    NSString *keyword = self.keyword ? self.keyword : @"";
    NSInteger orderAttrs = self.orderAttrs ? self.orderAttrs : 0;
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    NSInteger pageSize = 20;
    
    NSDictionary *parameters = @{
                                 @"pageNo":@(self.pageNo),
                                 @"pageSize":@(pageSize),
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"saId":[SISSUserAccount shared].saId,
                                 @"soId":[SISSUserAccount shared].soId,
                                 @"sobId":[SISSUserAccount shared].sobId,
                                 @"keyword":keyword,
                                 @"orderAttrs":@(orderAttrs),
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration,
                                 @"cooperationRange":self.cooperationRange
                                 };
    WeakSelf
    [kJsonRequestNetworkingManager requestFilterPassengerResourceCooperationWithParameters:parameters success:^(SISSBasePagingModel *baseModel) {
        
        NSArray *passengerCooperations = [NSArray yy_modelArrayWithClass:[SISSPassengerCooperationModel class] json:baseModel.data];
        
        if (weakSelf.passengerCooperationArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
            
            [weakSelf.passengerCooperationArr removeAllObjects];
        }
        
        for (int i = 0; i < passengerCooperations.count; i++) {
            
            [weakSelf.passengerCooperationArr addObject:passengerCooperations[i]];
        }
        
//        weakSelf.hintLabel.hidden = NO;
        weakSelf.hintLabel.text = [NSString stringWithFormat:@"共找到%zd条符合条件的信息",weakSelf.passengerCooperationArr.count];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.hintLabel.hidden = YES;
        });
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            weakSelf.tableView.mj_footer.hidden = baseModel.total == 0;
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (weakSelf.passengerCooperationArr.count >= baseModel.total) {
//                weakSelf.tableView.mj_footer.hidden = YES;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSLog(@"%@",error);
    } ];
}


#pragma mark - 设置UI
- (void)setupSubviews {
    
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, self.navigationHeight, SCREEN_WIDTH, 44) isHouseResource:NO isCooperation:YES];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 160;
    tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerNib:[UINib nibWithNibName:@"SISSFindPassengerCooperationCell" bundle:nil] forCellReuseIdentifier:findPassengerCooperationCellReuseID];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 排序按钮
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.layer.cornerRadius = 12;
    sortButton.layer.masksToBounds = YES;
    [sortButton setBackgroundImage:[ImageWithColor imageWithColor:[UIColor darkGrayColor]]  forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:15];
    sortButton.alpha = 0.8;
    [sortButton addTarget:self action:@selector(sortedButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sortButton];
    
    UILabel *hintLabel = [[UILabel alloc] init];
    hintLabel.textAlignment = NSTextAlignmentCenter;
    hintLabel.textColor = [UIColor whiteColor];
    hintLabel.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.8];
    hintLabel.layer.cornerRadius = 12;
    hintLabel.hidden = YES;
    hintLabel.layer.masksToBounds = YES;
    [self.view addSubview:hintLabel];
    self.hintLabel = hintLabel;
    
    // 自动布局
    CGSize sortBtnSize = CGSizeMake(66, 30);
    CGFloat margin = 10;
    CGFloat bottomViewHeight = 0;
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.filterView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.mas_equalTo(-bottomViewHeight);
    }];
    
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.size.mas_equalTo(CGSizeMake(250, 30));
        make.bottom.equalTo(weakSelf.view).offset(- 12 * margin);
    }];
    
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(-4 * margin);
        make.bottom.equalTo(weakSelf.view).offset(-8 * margin);
        make.size.mas_equalTo(sortBtnSize);
    }];
}



#pragma mark - 懒加载

- (NSMutableArray<SISSPassengerCooperationModel *> *)passengerCooperationArr {
    if (!_passengerCooperationArr) {
        _passengerCooperationArr = [NSMutableArray array];
    }
    return _passengerCooperationArr;
}

- (NSArray *)cooperationRange {
    if (!_cooperationRange) {
        _cooperationRange = [NSArray array];
    }
    return _cooperationRange;
}

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}


@end
